package com.zs.usc.service.impl;

import com.zs.usc.common.BusinessException;
import com.zs.usc.common.RestCode;
import com.zs.usc.entity.RoleInfo;
import com.zs.usc.entity.UserInfo;
import com.zs.usc.mapper.RoleInfoMapper;
import com.zs.usc.service.IRelationService;
import com.zs.usc.service.IRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zs.usc.service.IUserService;
import com.zs.usc.vo.CurrentUserInfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 * 用户角色表 服务实现类
 * </p>
 *
 * @author ZS
 * @since 2021-12-11
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleInfoMapper, RoleInfo> implements IRoleService {

    @Autowired
    private IUserService userService;

    @Autowired
    private RoleInfoMapper roleInfoMapper;

    @Autowired
    private IRelationService relationService;

    @Override
    public List<RoleInfo> listRoleByUserId(String uid, String serverNameUp) {
        // 1.判断用户是否存在
        UserInfo userInfo = userService.selectOptionalById(uid).orElseThrow(() -> new BusinessException("用户不存在！"));
        //2.获取用户角色
        CurrentUserInfo currentUserInfo = CurrentUserInfo.builder()
                .username(userInfo.getUserId()).build();
        return this.listRole(currentUserInfo, serverNameUp);
    }

    @Override
    public List<RoleInfo> listRole(CurrentUserInfo currentUserInfo, String serverNameUp) {
        // 服务标识不为空 判断用户是否有这个应用的权限
        if (StringUtils.isNotEmpty(serverNameUp) && !relationService.hasAppPerms(currentUserInfo.getUid(), serverNameUp)) {
            throw new BusinessException(RestCode.ERROR_AUTH_ERROR, "无权访问应用！");
        }
        // 查询该用户下的角色信息
        return this.roleInfoMapper.listRole(currentUserInfo.getUid(),serverNameUp);
    }
}
